// 显示主UI

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

import '../widget/vertical_text.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool darkModeOn = false;
  String textContent = '';
  String from = '';
  double singleLineWidth = 16;
  int numberOfSingleLineText = 10;

  @override
  void initState() {
    super.initState();
    loadTextContent();
  }

  @override
  void dispose() {
    // WidgetsBinding.instance.removeObserver(this as WidgetsBindingObserver);
    super.dispose();
  }

  Widget imageWidget() {
    return const CircleAvatar(
        backgroundColor: Colors.white70,
        foregroundImage: NetworkImage(
            'https://img.xjh.me/random_img.php?type=bg&ctype=nature&return=302'),
        radius: 90);
  }

  void loadTextContent() async {
    // https://v1.hitokoto.cn?c=k     https://v1.hitokoto.cn/?c=i
    var url = Uri.parse('https://v1.hitokoto.cn?c=k');
    var response = await http.post(url);

    Map<String, dynamic> respData = json.decode(response.body);

    setState(() {
      textContent = respData['hitokoto'] ?? "";
      from = respData['from_who'] ?? respData['from'] ?? "";
    });
  }

  Widget textWidget() {
    return VerticalText(
        textContent: textContent,
        from: from,
        singleLineWidth: singleLineWidth,
        numberOfSingleLineText: numberOfSingleLineText);
  }

  Widget buttonWidget() {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
          backgroundColor: const Color.fromARGB(0, 0, 05, 255),
          textStyle: const TextStyle(fontSize: 16)),
      child: const Text('下一句'),
      onPressed: () {
        loadTextContent();
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[imageWidget(), textWidget(), buttonWidget()],
        ),
      ),
    );
  }
}
